<template>
  <div>
    <input type="text"
      v-model="state.newListItem.id">
    <input type="text"
      v-model="state.newListItem.name">
    <button @click="handleAdd">add</button>
    <ul>
      <li v-for="(v, i) in state.dataList"
        :key="v.id"
        @click="handleRemove(i)">
        {{ v.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import {
  ref,
  reactive,
  shallowRef,
  shallowReactive,
  isRef,
  isReactive,
  isProxy,
  triggerRef,
  toRaw,
  markRaw,
} from "vue";
export default {
  setup() {
    //   非递归监听 shallowReactive,shallowRef  只有第一层为proxy ( triggerRef(state) 可强制更新 只对ref生效 对reactive不生效 )
    //   递归监听 reactive ,ref 每一层都包装成proxy
    // ! toRaw 取出原始数据 例如：
    // const a = {};
    // const a1 = reactive(a);
    // const a2 = toRaw(a1);
    // a2 === a;  true

    // ! markRaw 永远不被追踪
    // let a = {}
    // a = markRaw(a) // 禁止追踪后 更改数据UI也不会被改变
    const { state, handleRemove, handleAdd } = useList();
    const cout = ref(0);
    function testData() {
      console.log("isRef(state): ", isRef(state));
      console.log("isReactive(state): ", isReactive(state));
      console.log("isProxy(state): ", isProxy(state));
      console.log("isRef(cout): ", isRef(cout));
      console.log("isReactive(cout): ", isReactive(cout));
      console.log("isProxy(cout): ", isProxy(cout));
      // isRef(state):  false
      // isReactive(state):  true
      // isProxy(state):  true
      // isRef(cout):  true
      // isReactive(cout):  false
      // isProxy(cout):  false
    }
    testData();
    return {
      state,
      handleRemove,
      handleAdd,
    };
  },
};
function useList() {
  let state = reactive({
    newListItem: {
      id: "",
      name: "",
    },
    dataList: [
      {
        id: "1",
        name: "嗷呜",
      },
      {
        id: "2",
        name: "嗯哼",
      },
    ],
  });
  function handleRemove(index) {
    state.dataList = state.dataList.filter((v, i) => i !== index);
  }
  function handleAdd() {
    const { newListItem, dataList } = state;
    const newList = [...dataList];
    newList.push({ ...newListItem });
    state.dataList = newList;
    state.newListItem = { name: "", id: "" };
  }
  return {
    state,
    handleRemove,
    handleAdd,
  };
}
</script>

<style>
</style>